(function($) {
	
	window['View'] = {};
	
	/**
	 * 创建一个Form
	 */
	View.createForm = function(option) {
		var $form = option.$form;
		var onGetExtraParams = option.onGetExtraParams;
		var extraParams = option.extraParams;
		var onAfterSave = option.onAfterSave;
		var onFormExtraValidateCheck = option.onFormExtraValidateCheck;
		var onFormInValid = option.onFormInValid;
		
		/**
		 * 获取grid参数
		 * gridExtraParams : [{
					formGrid : $recordTestGrid, //grid对象
					isAllFiled : false, //是否所有的字段
					paramName : "recordTests", //提交的list参数
					paramFileds : ["record.id","","count","position","date","id"] //要提交的字段
				},{
					   	type:'grid',
						formGrid : $detectionGrid,//grid对象
						isAllFiled : true,//是否所有的字段
						paramName: ""//要提交的字段
				}],
		 * */
		var getGridParam = function(param, extraParam){
			var grid = extraParam.$grid;
			var selections = grid.datagrid('getRows');
			var isAllFiled = extraParam.isAllFiled;
			if(isAllFiled){
				if(selections != null) {
					$.each(selections,function(i,row){
						grid.datagrid('endEdit', i);
						for(var field in row){
							if(typeof row[field] != 'undefined')param[extraParam.paramName+"["+i+"]."+ field ] = row[field];
						}
					});
				}
			}else{
				var fields = extraParam.paramFileds;
				if(selections != null) {
					$.each(selections,function(i,row){
						if(fields != null && fields.length > 0){
							grid.datagrid('endEdit', i);
							for(var k=0;k<fields.length;k++){
								var field = fields[k];
								if(typeof row[field] != 'undefined'){
									param[extraParam.paramName+"["+i+"]."+ field ] = row[field];
								}
							}
						}
					});
				}
			}
		}
		/**{多选提交
				type:"combogrid",类型
				$combogrid: "employees"+pageId, //
				paramName:"employees",
				paramFiled: "id"
			}
		 * */
		var getCombogridParam = function(param, extraParam){
			var combogrid = extraParam.$combogrid;
			var ps = $("#"+combogrid).combogrid('getValues');
			for(var i=0;i<ps.length;i++){
				param[extraParam.paramName+"["+i+"]."+extraParam.paramFiled] = ps[i];
			}
		}
		$form.form({
			onSubmit : function(param) {
				if(typeof onFormExtraValidateCheck != 'undefined') {
					
					
					if(!onFormExtraValidateCheck()) {
						return false;
					}
				}
			
				if(typeof onGetExtraParams != 'undefined' ) {
					var params = onGetExtraParams();
					if(params != null) {
						for(attr in params) param[attr] = params[attr];
					}
				}
				
				if(typeof extraParams  != 'undefined' && extraParams.length >0) {
					for(var j=0;j<extraParams.length;j++){
						var extraParam = extraParams[j];
						if(extraParam.type.toUpperCase() == "GRID"){
							getGridParam(param, extraParam);
						}
						if(extraParam.type.toUpperCase() == "COMBOGRID"){//combogrid
							getCombogridParam(param, extraParam);
						}
					}
				}
				$.messager.progress({
					title : '提示',
					text : '数据处理中，请稍候....'
				});
				var isValid = $(this).form('validate');
				if (!isValid) {
					$.messager.progress('close');
					if(typeof onFormInValid != 'undefined') {
						onFormInValid();
					} else {
						$.messager.alert('提示','你录入的信息不完整，带红色波浪线标识的内容不能为空哦');
					}
				}
				return isValid;
			},
			success : function(result) {
				$.messager.progress('close');
				result = $.parseJSON(result);
				if(jqueryUtil.procException(result)) return;
				if (result.status) {
					if(typeof onAfterSave != 'undefined') onAfterSave(result);
					$.messager.show({
						title : result.title,
						msg : result.message,
						timeout : 1000 * 2
					});
				} else {
					$.messager.show({
						title :  result.title,
						msg : result.message,
						timeout : 1000 * 2
					});
				}
			} , failure : function() {
				alert("persistence failure")
			}
		});
	};
	
	View.createFormQueryDatagrid = function(option) {
		View._createFormQueryGrid(option,false);
	};
	
	View.createFormQueryTreegrid = function(option) {
		View._createFormQueryGrid(option,true);
	};
	
	/**
	 * 将表单与表格绑定
	 * 修改人:黄美春
	 * 修改时间：2015-08-06
	 * 修改描述：增加createFormQueryDatagrid的queryParams固定参数
	 * 原因由于清空按钮会导致hidden隐藏的固定参数也清空，所以做了这个修正，
	 * 如果不需要绑定查询表单则只需要增加formName即可
	 * 如下所示
	 * View.createFormQueryDatagrid(
			{
				//queryFrom的固定参数。不需要清空操作
				queryParams:{'detectionCompany.id':this.currentCompany >0 ? this.currentCompany:-1},
				//formId : "queryForm"+this.pageId,
				formName:"project",
				$grid : $grid,
				queryBtn :"queryBtn"+this.pageId,
				clearBtn : "clearBtn"+this.pageId
			}
		);
	 */
	View._createFormQueryGrid = function(option,isTreegrid) {
		var formId = option.formId;
		var $grid = option.$grid;
		var queryBtn = option.queryBtn;
		var clearBtn = option.clearBtn;
		var self = this;
		var $form = $("#"+formId);
		var formName = formId ? $form.attr('name') : option.formName;
		var pager = isTreegrid ? $grid.treegrid('getPager') : $grid.datagrid('getPager');			
		var options = isTreegrid ? $grid.treegrid("options") : $grid.datagrid("options");		
		//如果formId没找到formName则取当前配置formName
		if(typeof formName == 'undefined' && typeof option.formName != 'undefined'){
			formName = option.formName;
		}
		if(typeof formName == 'undefined') {
			formName = "form_"+new Date().getTime();
		} 
		var pagination = pager.data("pagination");
		var getQueryParams = function() {
			var queryParams = $form.form("serialize");
			var newQueryParams = {};
			for(var attr in queryParams) {
				if(queryParams[attr] != null && queryParams[attr] != '')
				newQueryParams[formName+"."+attr] = queryParams[attr]
			}
			
			if(pagination) {
				var pageOptions = pagination.options;  
				newQueryParams.page = 1;
				newQueryParams.total = pageOptions.total;
				newQueryParams.rows = pageOptions.pageSize;
			}
			if(typeof option.queryParams != 'undefined'){//queryParams是queryFrom的固定参数。不需要清空操作
				for(var attr in option.queryParams) {
					newQueryParams[formName+"."+attr] = option.queryParams[attr]
				}
			}
			newQueryParams['_formNameMark_'] = formName;
			return newQueryParams;
		};
		//var initQueryParams = {'_formNameMark_':formName};
		//options.queryParams = initQueryParams;
		var _queryParams = getQueryParams();
		var srcUrl = options.url;
		var url = jqueryUtil.appendURL(options.url,'_formNameMark_' ,formName);
		for(var attr in _queryParams)  {
			if(attr != 'page' && attr != 'rows' && attr != 'total')
			url = jqueryUtil.appendURL(url,attr ,_queryParams[attr]);
		}
		options.url = url;
		
		if(clearBtn)
			$("#"+clearBtn).click(function() {
				var notClearFldVal = {};
				if(typeof option.notClearFlds != null) {
					var flds = option.notClearFlds;
					var formData = $form.form('serialize');
					for(var fld in formData) {
						if($.inArray(fld,flds) != -1) {
							notClearFldVal[fld] = formData[fld];
						}
					}
				}	
				$form.form("clear");
				$form.form("load",notClearFldVal);
			});
		
		
		
		
		$("#"+queryBtn).click(function() {
			options.url = srcUrl;
			options.queryParams = getQueryParams();
			
			if(pagination) 
				self.autoLoad(pager,1);
			else {
				isTreegrid?$grid.treegrid('reload'):$grid.datagrid('reload')
			}
		});
		
		/**
		 * 自动触发分页的加载操作

		 * @param pager  各个控件对应的pagination组件
		 */
		this.autoLoad = function(pager,pageNumber) {
			var event = jQuery.Event("keydown");			//模拟一个键盘事件        
			event.keyCode = 13;								//keyCode=13是回车			
			pager.find('input.pagination-num').val(pageNumber);	//设置跳转页为当前指定页面			
			pager.find('input.pagination-num').trigger(event);
		}
	};
	
	View.deleteDatagridRow = function(option) {
		View._deleteGridRow(option,false);
	};
	
	View.deleteTreegridRow = function(option) {
		View._deleteGridRow(option,true);
	};
	
	
	View._deleteGridRow = function(option,isTreeGrid) {
		var url = option.url;
		var $grid = option.$grid;
		var onGetParams = option.onGetParams;
		var onAfterDelete = option.onAfterDelete;
		
		var node = isTreeGrid ? $grid.treegrid('getSelected') : $grid.datagrid('getSelected');
		var index = isTreeGrid ? $grid.treegrid('getRowIndex',node) : $grid.datagrid('getRowIndex',node);
		var params ;
		if(typeof onGetParams != 'undefined' && onGetParams != null) params = onGetParams(node);
		if (node) {
			$.messager.confirm("提示", "确定要删除记录吗?", function(r) {
				if (r) {
					$.post(url, params, function(rsp) {						
						if (rsp.status) {							
							if(typeof onAfterDelete != 'undefined' && onAfterDelete != null)
								onAfterDelete(node,index);
						}
						$.messager.show( {
							title : rsp.title,
							msg : rsp.message,
							timeout : 1000 * 2
						});
					}, "JSON").error(function() {
						$.messager.show( {
							title : "提示",
							msg : "提交错误了！",
							timeout : 1000 * 2
						});
					});
				}
			});
		} else {
			$.messager.show({
				title : "提示",
				msg : "请选择一行记录!",
				timeout : 1000 * 2
			});
		}
	};
	
	View.closeCurrentDlg = function() {				//关闭当前对话框
		$.modalDialog.handler.dialog('close');
	};
	
	View.createEditOrInsertDlg = function(option) {
		var isEditDlg = option.isEditDlg;	
		var onlyForView = option.onlyForView;
		var btnName = option.btnName;
		if (!btnName) {
			btnName = isEditDlg ? '修改保存' : '新增保存';
		}
		var buttons = [];
		if(typeof onlyForView == 'undefined' || !onlyForView) {
			buttons.push({text : btnName, iconCls : 'icon-save',
				handler : function() {if(typeof option.onOkClick != 'undefined') option.onOkClick();}
			});
		}
		buttons.push({text : '取消',iconCls : 'icon-cancel',
				handler : function() {
					if(option.onBeforeCancel) option.onBeforeCancel();
					$.modalDialog.handler.dialog('destroy');
					$.modalDialog.handler = undefined;
				}
			});
		$.modalDialog({
			title : option.title,
			width : option.width,
			height: option.height,
			href : option.href,
			onLoad : function() {
				if(typeof option.onPageLoad != 'undefined') option.onPageLoad();
			},
			buttons :buttons
		});
		return $.modalDialog.handler;	
	};
	
	/**
	 * 创建一个固定底部按钮的公共弹出框 by bjlong  
	 * 参考: reportSealQuantityDlg.js 文件 openDlg 方法
	 */
	View.createCustomButtonsDlg = function(option) {
		function getCustomButton(buttonAttr) {
			if(buttonAttr.text && (buttonAttr.id || buttonAttr.handler)) {
				return {
					'text' : buttonAttr.text,
					'id' : (buttonAttr.id ? buttonAttr.id : ""),
					'iconCls' : (buttonAttr.iconCls ? buttonAttr.iconCls : null),
					'bgColor' : (buttonAttr.bgColor ? buttonAttr.bgColor : null),
					'txtColor' : (buttonAttr.txtColor ? buttonAttr.txtColor : null),
					'handler' : function() {
						if(typeof buttonAttr.handler != 'undefined') buttonAttr.handler();
					}
				};
			}
			return null;
		}
		var buttons = [];
		if(option.buttons && option.buttons.length > 0){
			for(var i = 0; i < option.buttons.length; i++) {
				var currentButton = getCustomButton(option.buttons[i]);
				if(currentButton != null) {
					buttons.push(currentButton);
				}
			}
		}
		return $.customBtnsModalDialog({
			modal : option.modal,
			title : option.title,
			width : option.width,
			height: option.height,
			href : option.href,
			buttons :buttons,
			onLoad : function() {
				if(typeof option.onPageLoad != 'undefined') option.onPageLoad();
			},
			onClose : function() {
				if(typeof option.onClose != 'undefined') option.onClose();
			}
		});
	};
	
	View.createDictCombo = function(id,dictType,width) {
		width = width || 171;
		$("#"+id).combobox({
			width:width,
			url:"param/dict!getDictsCombo.action?type="+dictType,
			valueField: 'value',
			textField: 'text',
			editable:false,
			onSelect:function(value){
				
			}
		});
	};
	/**
	 * id html对象id
	 * url 查询grid请求
	 * initData 初始数据
	 * isMultiple 是否多选
	 * 修改：huangmeichun 
	 * 时间：2015-05-14
	 * 增加多选
	 * 修改：huangmeichun 
	 * 时间：2016-03-22
	 * createComboGrid修改queryField 代替GRID的name，增加onChange方法
	 */
View.createComboGrid = function(id,url,initData,isMultiple,_option) {
	var option = _option ? _option : {};
	var lastQueryKey = null;	//记录上次提交的关键词，防止重复提交
	var columns = [];
	var queryField = option.queryField ? option.queryField : 'name';
	if(isMultiple && isMultiple == true){
		columns = [[ {field:'ck',checkbox:true},{field:'name',title:'名称',width:100} ]];
	}else{
		isMultiple = false;
		columns =  [[{field:queryField,title:'名称',width:100} ]];
	}
	columns = option.columns ? option.columns : columns;
	$('#'+id).combogrid({  
        panelWidth: option.panelWidth ? option.panelWidth : 400,
        width:option.width ? option.width : 170,
		onChange : option.onChange? option.onChange:function(newValue, oldValue){},
        idField:'id', //ID字段  
        textField:queryField, //显示的字段  
        delay:1000,
        fitColumns: true,  
        multiple: isMultiple,
        pagination : true,//是否分页  
        rownumbers:true,//序号 
         
        fit: true,//自动大小  
        pageSize: 10,//每页显示的记录条数，默认为10  
        pageList: [10],//可以设置每页记录条数的列表  
        method:'post',
        columns: columns,
        
        
        keyHandler:{
		up: function(){
			var row = $(this).combogrid('grid').datagrid('getSelected');
			var rowIndex = $(this).combogrid('grid').datagrid('getRowIndex',row);
			var nextRowIndex = rowIndex;
			if(rowIndex>0){
				nextRowIndex = rowIndex-1;
				$(this).combogrid('grid').datagrid('selectRow',nextRowIndex);
			}
		},  
		down: function () { 
			var rows = $(this).combogrid('grid').datagrid('getRows');
			var row = $(this).combogrid('grid').datagrid('getSelected');
			var rowIndex = $(this).combogrid('grid').datagrid('getRowIndex',row);
			var nextRowIndex = rowIndex;
			if(rows.length >rowIndex+1){
				nextRowIndex = rowIndex+1;
				$(this).combogrid('grid').datagrid('selectRow',nextRowIndex);
			}
		},  
		enter: function(){
			var param = "";
			if(!isMultiple){
				param = $.trim($(this).combogrid('getText'));
			}
			query($(this).combogrid('grid'), param,url);
		},
		query: function(q) {
			var param = "";
			if(!isMultiple){
				param = $.trim($(this).combogrid('getText'));
			}
			query($(this).combogrid('grid'), param,url);
			return false;
		}
       },
       onLoadSuccess : function(data) {
    	   if(!isMultiple){
    		   if(data.rows.length > 0) {
    			   if($.trim($(this).combogrid('getText')) != '')
    				   $(this).combogrid('grid').datagrid('selectRow',0);
    		   } else {
    			   var noRcd = {};
    			   noRcd[queryField] = "查询无记录"
    			   $(this).combogrid('grid').datagrid('loadData',{total:1,rows:[noRcd]});
    			   $(this).combogrid('setValue',initData ? initData.id : '');
    			   $(this).combogrid('setText',initData ? initData["'"+queryField+"'"] : '');
    			   
    		   }
    	   }
       },
       
       onShowPanel: function (a,b,c) {
    	   var param = "";
			if(!isMultiple){
				param = $.trim($(this).combogrid('getText'));
			}
			query($(this).combogrid('grid'), param,url);
       }, 
       onSelect: function (index, row) { 
    	  if(!row.id) row["'"+queryField+"'"] = '';				//防止选中”查询无记录"行
    	  else initData = row;
       }  
    });  
	
	if(initData){
		var rows = [initData];
		if(isMultiple == true) rows = initData;
		$('#'+id).combogrid('grid').datagrid('loadData',({total:1,rows: rows}));
	}
	
	function query(grid,text,url) {
		if(lastQueryKey == text) return;		//防止重复提交查询
		var queryParam = {};
		//加上默认查询参数黄美春2015-07-30
		if(typeof option.queryParams != 'undefined'){
			$.each( option.queryParams, function(key, val){
				queryParam['default_form.'+key]  = val;
			});
		}
  	    queryParam._formNameMark_ = 'default_form';
  	    if(text != null) queryParam['default_form.'+queryField]  = text;
        $(grid).datagrid('options').queryParams = queryParam;
        $(grid).datagrid('options').url= url;  
        $(grid).datagrid('load');  
        lastQueryKey = text;
	};
};
	
})(jQuery);